import {
	createWS
} from '@/api/index.js'
import {wsSend} from '@/utils/index.js'


// ws连接类
export class Ws {
	constructor(url) {
		this.socketTask = {},
			this.wsOpen = false,
			this.timeout = 4000,
			this.interval = 8000,
			this.clientTimer = null,
			this.severTimer = null,
			this.reconnectNum = 0,
			this.reconnectLimit = 5,
			this.url = url
	}
	// ws连接
	createWebsocket() {
		this.socketTask = createWS(this.url)
		this.wsListener()
	}
	// ws监听
	wsListener() {
		this.socketTask.addEventListener('open',() => {
			this.wsOpen = true
			// this.heartStart()
		})
		this.socketTask.addEventListener('message',() => {
			// this.heartStart()
		})
		this.socketTask.addEventListener('close',() => {
			this.wsOpen = false
		})
		this.socketTask.addEventListener('error',(e) => {
			throw `ws报错${e}`
		})
		
	}
	heartStart() {
		this.serverTimer && clearTimeout(this.serverTimer);
		this.clientTimer && clearInterval(this.clientTimer);
		this.clientTimer = setInterval(() => {
			//发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
			let params = {
				contentType:'0x25',
				content: '小会场心跳'
			}
			wsSend(this.socketTask, params)
			//定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
			this.serverTimer = setTimeout(() => {
				this.socketTask.close();
				this.reConnect();
			}, this.timeout);
		}, this.interval);
	}
	reConnect() {
		if (this.reconnectNum >= this.reconnectLimit) {
			this.serverTimer && clearTimeout(this.serverTimer);
			this.clientTimer && clearInterval(this.clientTimer);
			this.reconnectNum = 0;
			return;
		}
		this.reconnectNum++;
		this.createWebsocket()
	}
}
